<?php
class Obj_System_SearchIndex
{
	protected static $t;
	
	public static function __init() {
		self::$t = new Obj_DBTable_SearchIndex();
	}
	
	public static function write() {
		$n = func_num_args();
		if ($n < 3) {
			throw new Zend_Exception(_('В эту функцию нужно передать как минимум три параметра: $id, $type, $content'));
		}
		$arParams = func_get_args();
		$id = $arParams[0];
		$type = $arParams[1];
		$s = '';
		$n = count($arParams);
		for ($i = 2; $i < $n; $i++) $s .= strip_tags($arParams[$i]).' ';
		self::delete($id, $type);
		if (self::$t->write($id, $type, $s) !== false) return self::$t->execTime;
		return false;
	}
	
	public static function delete($id, $type) {
		self::$t->delete('ContentID = '.intval($id).' AND ContentType = '.intval($type));
	}
	
	public static function search($phrase) {
		$arResult = self::$t->search($phrase);
		$highlight = str_replace(" ", "|", $phrase);
		$highlight = str_replace("/", "\/", $highlight);
		$delta = 1000;
		foreach ($arResult as $k => $v) {
			$quote = preg_replace("/$highlight/imsUu", '<span style="color: #CC0000">$0</span>', $v['Content']);
			$i = strpos($quote, '<span style="color: #CC0000">');
			if ($i === FALSE) {
				$arResult[$k]['quote'] = $quote;
				continue;
			}
			$s = $i - $delta / 2;
			while ($s > 0 && $s > $i - $delta && !ctype_space($quote[$s])) {
				$s--;
			}
			if ($s < 0) $s = 0;
			$e = $i + $delta / 2;
			$n = strlen($quote);
			while ($e < $n && $e < $i + $delta && !ctype_space($quote[$e])) {
				$e++;
			}
			$quote = strip_tags(substr($quote, $s, $e - $s));
			$quote = preg_replace("/$highlight/imsUu", '<span style="color: #CC0000">$0</span>', $quote);
			$arResult[$k]['quote'] = '... '.$quote.' ...';
		}
		return $arResult;
	}
	
} Obj_System_SearchIndex::__init();

